package com.sc.nft.dao;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sc.nft.entity.ShowLevel;
import com.sc.nft.entity.vo.ShowLevelVO;
import com.sc.nft.mapper.ShowLevelMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * (sc_show_level)数据DAO
 *
 * @author rdg
 * @description 由 Mybatisplus Code Generator 创建
 * @since 2022-08-19 11:10:54
 */
@Slf4j
@Repository
public class ShowLevelDao extends ServiceImpl<ShowLevelMapper, ShowLevel> {
    @Resource
    private  RedisTemplate redisTemplate;

    public List<ShowLevelVO> getAllShowLevel() {
        return baseMapper.getAllShowLevel();
    }

    public List<ShowLevelVO> getAllShowLevelByApp() {
        return baseMapper.getAllShowLevelByApp();
    }

    public ShowLevel getShowNameById(Long showLevel) {
        LambdaQueryWrapper<ShowLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShowLevel::getId, showLevel);
        wrapper.select(ShowLevel::getShowLevelName);
        return getOne(wrapper);
    }

    public ShowLevel getByShowLevelCash(Integer showLevel) {
        String key = StrUtil.format("ShowLevel:getByShowLevelCash:{}", showLevel);
        if (redisTemplate.hasKey(key)) {
            String data = (String) redisTemplate.opsForValue().get(key);
            return JSON.parseObject(data, ShowLevel.class);
        }
        LambdaQueryWrapper<ShowLevel> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShowLevel::getId, showLevel);
        ShowLevel one = getOne(wrapper);
        if (BeanUtil.isNotEmpty(one)) {
            redisTemplate.opsForValue().set(key,JSON.toJSONString(one),3, TimeUnit.HOURS);
        }
        return one;
    }
}